package com.example.sse.demos.web;

import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

@RestController
@Slf4j
public class SSETwoController {

    // 高性能事件流接口
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEvents(@RequestParam String userId) {
        return Flux.interval(Duration.ofMillis(100)) // 控制推送频率
                .map(sequence -> generateEventData(userId, sequence)) // 生成事件数据
                .doOnCancel(() -> cleanupResource(userId)) // 连接关闭时清理资源
                .onErrorResume(e -> {
                    log.error("SSE error: {}", e.getMessage());
                    return Flux.empty();
                });
    }

    private String generateEventData(String userId, Long sequence) {
        // 模拟实时数据（替换为实际业务逻辑）
        return "data: {\"user\":\"" + userId
                + "\", \"time\":\"" + System.currentTimeMillis()
                + "\", \"seq\":\"" + sequence + "\"}\n\n";
    }

    private void cleanupResource(String userId) {
        // 释放用户相关资源
        log.info("Cleanup resources for user: {}", userId);
    }



    @GetMapping(value = "/oneStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEventsOneStream() {
        return Flux.interval(Duration.ofMillis(3000)) // 控制推送频率
                .map(sequence -> generateEventDataOneStream()) // 生成事件数据
//                .doOnCancel(() -> cleanupResource(userId)) // 连接关闭时清理资源
                .onErrorResume(e -> {
                    log.error("SSE error: {}", e.getMessage());
                    return Flux.empty();
                });
    }


    private String generateEventDataOneStream() {
        String data = "Data at " + System.currentTimeMillis();
        // 模拟实时数据（替换为实际业务逻辑）
        return data;
    }
}
